#ifndef __MY_POLL__
#define __MY_POLL__
#include <iostream>
#include <mutex>

namespace wzh
{
#define N 5
#define blockSize 1024
	template <typename T>
	class MemoryPoll
	{
	public:
		static MemoryPoll* getInstace()
		{
			if (instace_ == nullptr)
			{
				mtx_.lock();
				if (instace_ == nullptr)
				{
					instace_ = new MemoryPoll;
				}
				mtx_.unlock();
			}
			return instace_;
		}

		char* getMemory(size_t size)
		{
			if (size <= size_ && use_block_ < total_block_)
			{
				for (auto& b : arr_)
				{
					if (b != nullptr)
					{
						char* tmp = b;
						b = nullptr;
						use_block_++;
						return tmp;
					}
				}
			}
			return nullptr;
		}

		bool freeMemory(char* block)
		{
			for (auto& b : arr_)
			{
				if (b == nullptr)
				{
					b = block;
					use_block_--;
					break;
				}
			}
			return true;
		}

	private:
		static MemoryPoll* instace_;
		static std::mutex mtx_;

		MemoryPoll()
			:total_block_(N), use_block_(0), size_(blockSize)
		{
			for (int i = 0; i < N; i++)
			{
				arr_[i] = new T[blockSize];
			}
		}
		~MemoryPoll()
		{
			for (int i = 0; i < N; i++)
			{
				delete(arr_[i]);
			}
		}
	private:
		size_t size_;
		size_t total_block_;
		size_t use_block_;
		T* arr_[N];
	};
	template <typename T>
	MemoryPoll<T>* MemoryPoll<T>::instace_ = nullptr;
	template <typename T>
	std::mutex wzh::MemoryPoll<T>::mtx_;
}


#endif // !__MY_POLL__

